import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import VueCookies from 'vue-cookies'
import router from '@/router'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 6000 // 请求超时时间
})
// 判断环境prod 或者 preview 是 true 时，异常跳转
let isProd = process.env.NODE_ENV === 'production' || process.env.VUE_APP_PREVIEW !== 'true'

const err = (error) => {
  // debugger
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 404) {
      notification.error({
        message: 'Not Find',
        description: data.message
      })
      if(isProd) {
        router.push({ path: '/exception/404' })
      }
    }
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
      if(isProd) {
        router.push({ path: '/exception/403' })
      }
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: data.code || 'Unauthorized',
        description: data.msg || 'Authorization verification failed'
      })
      if(isProd) {
        router.push({ path: '/exception/401' })
      }
    }
    if (error.response.status === 500) {
      notification.error({
        message: 'Server Error',
        description: data.message
      })
      if(isProd) {
        router.push({ path: '/exception/500' })
      }
    }
  }

  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  let token = Vue.ls.get(ACCESS_TOKEN)
  if (!token && VueCookies.isKey(ACCESS_TOKEN)) {
    token = VueCookies.get(ACCESS_TOKEN)
  }
  if (token) {
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers[ACCESS_TOKEN] = token
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
